package com.sky.aspect;

import com.sky.dto.DishDTO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * sky-take-out
 * com.sky.aspect
 * 清除缓存切面类
 *
 * @author Ablecisi
 * @version 1.0
 * 2025/4/4
 * 18:10
 */
@Aspect
@Component
@Slf4j
public class ClearCacheAspect {
    private final RedisTemplate<String, Object> redisTemplate;

    private static final String DISH_CACHE_PREFIX = "dish_";

    @Autowired
    public ClearCacheAspect(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Pointcut("execution(* com.sky.controller..*.*(..)) && @annotation(com.sky.annotation.ClearCache)")
    private void clearCachePointCut() {
    }

    /**
     * 清除缓存
     * @param joinPoint 切入点
     */
    @Before("clearCachePointCut()")
    public void clearCache(JoinPoint joinPoint) {
        log.info("开始清除缓存...");
        // 获取参数
        Object[] args = joinPoint.getArgs();
        // 如果参数.getCategoryId()不为空，则清除对应的缓存
        try {
            Long categoryId = ((DishDTO)args[0]).getCategoryId();
            if (categoryId != null) {
                log.info("清除缓存，categoryId: {}", categoryId);
                // 清除缓存
                redisTemplate.delete(DISH_CACHE_PREFIX + categoryId);
            } else {
                log.info("清除所有缓存");
                // 清除所有缓存
                redisTemplate.delete(DISH_CACHE_PREFIX + "*");
            }
        } catch (Exception e) {
            // 如果参数不是DishDTO，则清除所有缓存
            log.info("参数不是DishDTO, 清除所有缓存");
            redisTemplate.delete(DISH_CACHE_PREFIX + "*");
        }
    }
}
